package com.ctgu.springshiro.dao;

import com.ctgu.springshiro.entity.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;
import java.util.Set;

@Mapper
public interface RoleDao {

    @Select("select * from role r " +
            "   left join user_roles ur on r.id = ur.role_id" +
            "   where ur.user_id = #{userId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "roleName", column = "rolename"),
            @Result(property = "permissions",
                    column = "id",
                    many = @Many(select = "com.ctgu.springshiro.dao.PermissionDao.getPermissionsByRoleId",
                            fetchType = FetchType.LAZY))
    })
    Set<Role> getRolesByUserId(int userId);

    @Select("select * from role")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "roleName", column = "rolename"),
            @Result(property = "uid", column = "user_id"),
            @Result(property = "user",
                    column = "user_id",
                    one = @One(select = "com.ctgu.springshiro.dao.UserDao.findById",
                            fetchType = FetchType.LAZY))
    })
    List<Role> getAllRoles();

    @Update("update user set rolename=#{rolename} where id=#{id}")
    void updateRole(Role role);
}
